import 'package:flutter/material.dart';
import 'package:flutter_bmfutils/BaiduMap/bmfmap_utils.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:loxen/dialog/toast.dart';
import 'package:loxen/mode/order_detail_mode.dart';
import 'package:loxen/utils/color.dart';
import 'package:loxen/utils/config.dart';

import 'package:flutter_bmfbase/BaiduMap/bmfmap_base.dart';
import 'package:flutter_bmflocation/bdmap_location_flutter_plugin.dart';
import 'package:flutter_bmflocation/flutter_baidu_location.dart';
import 'package:flutter_bmflocation/flutter_baidu_location_android_option.dart';
import 'package:flutter_bmflocation/flutter_baidu_location_ios_option.dart';
import 'package:loxen/utils/map_url_util.dart';
import 'package:loxen/utils/time_util.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';

class OrderDetailTypeCard extends StatelessWidget {
  final bool staff;
  final OrderDetailMode orderDetailMode;
  final ValueNotifier<int> _size = ValueNotifier(0);

  OrderDetailTypeCard({Key key, this.orderDetailMode, this.staff = false}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    Widget page;
    if (orderDetailMode.mode == '1') {
      page = tongChengCard(context);
    } else if (orderDetailMode.mode == '2') {
      if (!staff) {
        initLocation(context);
      }
      page = daoDianCard(context);
    } else if (orderDetailMode.mode == '3') {
      page = kuaiDiCard(context);
    } else {
      page = Text('未知状态 =>${orderDetailMode.mode}');
    }
    return Card(
      elevation: 5,
      child: Container(
        padding: EdgeInsets.fromLTRB(20.w, 16.h, 20.w, 16.h),
        width: double.infinity,
        child: page,
      ),
    );
  }

  Widget daoDianCard(BuildContext context) {
    return Column(
      children: [
        Row(
          children: [
            Image.asset(
              'images/daodian.png',
              width: 60.w,
              height: 60.w,
            ),
            Padding(
              padding: EdgeInsets.only(left: 10.w),
              child: Text(
                '到点取样',
                style: TextStyle(
                  fontSize: 32.sp,
                  fontWeight: FontWeight.bold,
                  color: Colours.main_text,
                ),
              ),
            )
          ],
        ),
        Padding(
          padding: EdgeInsets.only(top: 20.h),
          child: Row(
            children: [
              Container(
                width: 70.w,
              ),
              Text(
                TimeUtil.getStringTime(orderDetailMode.startTime, orderDetailMode.endTime),
                style: TextStyle(
                  fontSize: 28.sp,
                  color: Colours.main_text,
                ),
              ),
            ],
          ),
        ),
        Padding(
          padding: EdgeInsets.only(top: 30.h, bottom: 30.h),
          child: Divider(
            height: 1.h,
          ),
        ),
        Padding(
          padding: EdgeInsets.only(bottom: 35.h),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              Expanded(
                child: Text(
                  orderDetailMode.serviceCentre.name,
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 28.sp,
                    color: Colours.main_text,
                  ),
                ),
              ),
              staff
                  ? Constants.empty
                  : ValueListenableProvider<int>.value(
                      value: _size,
                      builder: (context, _) {
                        int size = context.watch<int>();
                        String text;
                        if (size > 1000) {
                          text = "${size / 1000}km";
                        } else {
                          text = "${size}m";
                        }
                        return Text(
                          text,
                          style: TextStyle(
                            fontWeight: FontWeight.bold,
                            fontSize: 24.sp,
                            color: Colours.main_text,
                          ),
                        );
                      },
                    )
            ],
          ),
        ),
        Padding(
          padding: EdgeInsets.only(bottom: 20.h),
          child: Row(
            children: [
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      orderDetailMode.serviceCentre.getCityString(),
                      style: TextStyle(
                        fontSize: 24.sp,
                        color: Colours.main_text,
                      ),
                    ),
                    Text(
                      orderDetailMode.serviceCentre.address,
                      style: TextStyle(
                        fontSize: 24.sp,
                        color: Colours.main_text,
                      ),
                    ),
                  ],
                ),
              ),
              staff
                  ? Constants.empty
                  : Padding(
                      padding: EdgeInsets.only(left: 50.w),
                      child: InkWell(
                        onTap: () {
                          MapUtil.gotoBaiduMap(orderDetailMode.serviceCentre.lng,
                              orderDetailMode.serviceCentre.lat, context);
                        },
                        child: Container(
                          child: Center(
                            child: Text(
                              '到这里去',
                              style: TextStyle(
                                fontSize: 24.sp,
                                color: Colours.app_main,
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
            ],
          ),
        ),
        Row(
          children: [
            Text(
              '联系电话：',
              style: TextStyle(
                fontSize: 28.sp,
                color: Colours.main_text,
              ),
            ),
            Text(
              orderDetailMode.serviceCentre.mobile,
              style:
                  TextStyle(fontSize: 28.sp, color: Colours.main_text, fontWeight: FontWeight.bold),
            ),
            Expanded(
              child: Constants.empty,
            ),
            staff
                ? Constants.empty
                : InkWell(
                    onTap: () async {
                      String url = 'tel:${orderDetailMode.serviceCentre.mobile}';
                      bool canLaunchUrl = await canLaunch(url);
                      if (!canLaunchUrl) {
                        Toast.show('拨号失败', context);
                        return;
                      }
                      await launch(url);
                    },
                    child: Image.asset(
                      'images/telephone_icon.png',
                      width: 34.w,
                      height: 34.w,
                    ),
                  ),
          ],
        )
      ],
    );
  }

  Widget tongChengCard(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Image.asset(
              'images/tongcheng.png',
              width: 60.w,
              height: 60.w,
            ),
            Padding(
              padding: EdgeInsets.only(left: 10.w),
              child: Text(
                '同城送样',
                style: TextStyle(
                  fontSize: 32.sp,
                  fontWeight: FontWeight.bold,
                  color: Colours.main_text,
                ),
              ),
            )
          ],
        ),
        Padding(
          padding: EdgeInsets.only(top: 20.h),
          child: Row(
            children: [
              Container(
                width: 70.w,
              ),
              Text(
                TimeUtil.getStringTime(orderDetailMode.startTime, orderDetailMode.endTime),
                style: TextStyle(
                  fontSize: 28.sp,
                  color: Colours.main_text,
                ),
              ),
            ],
          ),
        ),
        Padding(
          padding: EdgeInsets.only(top: 30.h, bottom: 30.h),
          child: Divider(
            height: 1.h,
          ),
        ),
        Padding(
          padding: EdgeInsets.only(bottom: 20.h),
          child: Text(
            orderDetailMode.address.getStringCity(),
            style: TextStyle(
              fontSize: 24.sp,
              color: Colours.main_text,
            ),
          ),
        ),
        Padding(
          padding: EdgeInsets.only(bottom: 20.h),
          child: Text(
            orderDetailMode.address.address,
            style: TextStyle(
              fontSize: 28.sp,
              fontWeight: FontWeight.bold,
              color: Colours.main_text,
            ),
          ),
        ),
        Text(
          '${orderDetailMode.address.signer_name} ${orderDetailMode.address.signer_mobile}',
          maxLines: 1,
          style: TextStyle(
            fontSize: 24.sp,
            color: Colours.main_text,
          ),
        ),
        Padding(
          padding: EdgeInsets.only(top: 30.h, bottom: 30.h),
          child: Divider(
            height: 1.h,
          ),
        ),
        createStaff(context),
      ],
    );
  }

  Widget kuaiDiCard(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Image.asset(
              'images/kuaidi.png',
              width: 55.w,
              height: 55.w,
            ),
            Padding(
              padding: EdgeInsets.only(left: 20.w),
              child: Text(
                '快递寄样',
                style: TextStyle(
                  fontSize: 32.sp,
                  fontWeight: FontWeight.bold,
                  color: Colours.main_text,
                ),
              ),
            )
          ],
        ),
        Padding(
          padding: EdgeInsets.only(top: 30.h, bottom: 30.h),
          child: Divider(
            height: 1.h,
          ),
        ),
        Padding(
          padding: EdgeInsets.only(bottom: 20.h),
          child: Text(
            orderDetailMode.address.getStringCity(),
            style: TextStyle(
              fontSize: 24.sp,
              color: Colours.main_text,
            ),
          ),
        ),
        Padding(
          padding: EdgeInsets.only(bottom: 20.h),
          child: Text(
            orderDetailMode.address.address,
            style: TextStyle(
              fontSize: 28.sp,
              fontWeight: FontWeight.bold,
              color: Colours.main_text,
            ),
          ),
        ),
        Text(
          '${orderDetailMode.address.signer_name} ${orderDetailMode.address.signer_mobile}',
          maxLines: 1,
          style: TextStyle(
            fontSize: 24.sp,
            color: Colours.main_text,
          ),
        )
      ],
    );
  }

  void initLocation(BuildContext context) async {
    bool initLocationBool = false;
    LocationFlutterPlugin _locationPlugin = LocationFlutterPlugin();
    _locationPlugin.onResultCallback().listen((event) async {
      if (initLocationBool) return;
      BaiduLocation _baiduLocation = BaiduLocation.fromMap(event);
      if (_baiduLocation.longitude != null) {
        initLocationBool = true;
        _locationPlugin.stopLocation();
      }
      double my = await BMFCalculateUtils.getLocationDistance(
          BMFCoordinate(_baiduLocation.latitude, _baiduLocation.longitude),
          BMFCoordinate(double.parse(orderDetailMode.serviceCentre.lat),
              double.parse(orderDetailMode.serviceCentre.lng)));
      _size.value = my.toInt();
    });

    bool data = await _locationPlugin.requestPermission();
    if (data) {
      BaiduLocationAndroidOption androidOption = BaiduLocationAndroidOption();
      androidOption.setCoorType("bd09ll"); // 设置返回的位置坐标系类型
      androidOption.setIsNeedAltitude(true); // 设置是否需要返回海拔高度信息
      androidOption.setIsNeedAddres(true); // 设置是否需要返回地址信息
      androidOption.setIsNeedLocationPoiList(true); // 设置是否需要返回周边poi信息
      androidOption.setIsNeedNewVersionRgc(true); // 设置是否需要返回最新版本rgc信息
      androidOption.setIsNeedLocationDescribe(true); // 设置是否需要返回位置描述
      androidOption.setOpenGps(true); // 设置是否需要使用gps
      androidOption.setLocationMode(LocationMode.Hight_Accuracy); // 设置定位模式
      androidOption.setScanspan(1000); // 设置发起定位请求时间间隔

      Map androidMap = androidOption.getMap();

      /// ios 端设置定位参数
      BaiduLocationIOSOption iosOption = BaiduLocationIOSOption();
      iosOption.setIsNeedNewVersionRgc(true); // 设置是否需要返回最新版本rgc信息
      iosOption.setBMKLocationCoordinateType("BMKLocationCoordinateTypeBMK09LL"); // 设置返回的位置坐标系类型
      iosOption.setActivityType("CLActivityTypeAutomotiveNavigation"); // 设置应用位置类型
      iosOption.setLocationTimeout(10); // 设置位置获取超时时间
      iosOption.setDesiredAccuracy("kCLLocationAccuracyBest"); // 设置预期精度参数
      iosOption.setReGeocodeTimeout(10); // 设置获取地址信息超时时间
      iosOption.setDistanceFilter(100); // 设置定位最小更新距离
      iosOption.setAllowsBackgroundLocationUpdates(true); // 是否允许后台定位
      iosOption.setPauseLocUpdateAutomatically(true); //  定位是否会被系统自动暂停

      Map iosMap = iosOption.getMap();

      _locationPlugin.prepareLoc(androidMap, iosMap);
      _locationPlugin.startLocation();
    } else {
      Toast.show('定位权限失败', context);
    }
  }

  Widget createStaff(BuildContext context) {
    if (staff) {
      return Constants.empty;
    } else {
      return orderDetailMode.staff != null
          ? Container(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Image.asset(
                        'images/head_portrait.png',
                        width: 80.w,
                        height: 80.w,
                      ),
                      Padding(
                        padding: EdgeInsets.only(left: 20.w),
                        child: Text(
                          '${orderDetailMode.staff.mode}-${orderDetailMode.staff.name}',
                          style: TextStyle(
                            fontSize: 32.sp,
                            fontWeight: FontWeight.bold,
                            color: Colours.main_text,
                          ),
                        ),
                      )
                    ],
                  ),
                  Padding(
                    padding: EdgeInsets.only(right: 160.w),
                    child: Row(
                      children: [
                        Container(
                          width: 100.w,
                        ),
                        Expanded(
                          child: Text(
                            '您好，我是本次为您进行同城送样 的业务员${orderDetailMode.staff.name}。',
                            style: TextStyle(
                              fontSize: 28.sp,
                              color: Colours.main_text,
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.only(top: 20.h),
                    child: Row(
                      children: [
                        Container(
                          width: 100.w,
                        ),
                        Container(
                          padding: EdgeInsets.fromLTRB(20.w, 12.h, 20.w, 12.h),
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.all(Radius.circular(40.h)),
                            color: Color(0xFFFFF5E1),
                          ),
                          child: Center(
                            child: Text(
                              '业务员14天内体温正常',
                              style: TextStyle(
                                fontSize: 22.sp,
                                color: Color(0xFFFCAD08),
                              ),
                            ),
                          ),
                        )
                      ],
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.only(top: 20.h),
                    child: Row(
                      children: [
                        Container(
                          width: 100.w,
                        ),
                        Text(
                          '联系电话：',
                          style: TextStyle(
                            fontSize: 28.sp,
                            color: Colours.main_text,
                          ),
                        ),
                        Text(
                          orderDetailMode.staff.telephone,
                          style: TextStyle(
                              fontSize: 28.sp,
                              color: Colours.main_text,
                              fontWeight: FontWeight.bold),
                        ),
                        Expanded(
                          child: Constants.empty,
                        ),
                        InkWell(
                          onTap: () async {
                            String url = 'tel:${orderDetailMode.staff.telephone}';
                            bool canLaunchUrl = await canLaunch(url);
                            if (!canLaunchUrl) {
                              Toast.show('拨号失败', context);
                              return;
                            }
                            await launch(url);
                          },
                          child: Image.asset(
                            'images/telephone_icon.png',
                            width: 34.w,
                            height: 34.w,
                          ),
                        )
                      ],
                    ),
                  ),
                ],
              ),
            )
          : Text(
              '等待服务中心安排业务员',
              style: TextStyle(
                fontSize: 28.sp,
                fontWeight: FontWeight.bold,
                color: Colours.main_text,
              ),
            );
    }
  }
}
